<template>
  <div class="table-demo">
    <div class="operation-bar">
      <el-upload
        action=""
        :auto-upload="false"
        :show-file-list="false"
        accept=".xlsx,.xls"
        @change="handleFileChange"
      >
        <el-button type="primary">导入Excel</el-button>
      </el-upload>
    </div>

    <enhanced-table
      ref="tableRef"
      :data="tableData"
      :columns="columns"
      row-key="id"
      :merge-columns="['department']"
      selection-type="multiple"
      :index-key="'序号'"
      v-model:show-index="showIndexColumn"
      @selection-change="handleSelectionChange"
      @row-drag="handleRowDrag"
    >
      <!-- 自定义列模板示例 -->
      <template #action="{ row }">
        <el-button type="text" @click="handleEdit(row)">编辑</el-button>
        <el-button type="text" @click="handleDelete(row)">删除</el-button>
      </template>
    </enhanced-table>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import EnhancedTable from '../components/EnhancedTable.vue'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'
import type { UploadFile } from 'element-plus'
import type { TableColumn } from '../components/EnhancedTable.vue'
const showIndexColumn = ref(true)
// 表格列配置
const columns: TableColumn[] = [
  {
    label: '部门',
    prop: 'department',
    fixed: 'left' as const,
  },
  {
    label: '个人信息',
    prop: 'personalInfo',
    children: [
      {
        label: '姓名',
        prop: 'name',
        validator: (value: any) => value && value.length >= 2
      },
      {
        label: '年龄',
        prop: 'age',
        validator: (value: number) => Boolean(value && value >= 18 && value <= 65)
      }
    ]
  },
  {
    label: '联系方式',
    prop: 'contact', // 添加 prop 属性
    children: [
      {
        label: '电话',
        prop: 'phone',
        validator: (value: string) => /^1[3-9]\d{9}$/.test(value)
      },
      {
        label: '邮箱',
        prop: 'email',
        validator: (value: string) => /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value)
      }
    ]
  },
  {
    label: '操作',
    prop: 'action',
    fixed: 'right',
    width: 120
  }
]

// 模拟数据
const tableData = ref([
  {
    id: 1,
    序号: 1,
    department: '技术部',
    name: '张三',
    age: 28,
    phone: '13800138000',
    email: 'zhangsan@example.com'
  },
  {
    id: 2,
    序号: 2,
    department: '科研部',
    name: '李四',
    age: 32,
    phone: '13800138001',
    email: 'lisi@example.com'
  },
  {
    id: 3,
    序号: 3,
    department: '技术部',
    name: '王五',
    age: 25,
    phone: '13800138002',
    email: 'wangwu@example.com'
  },
  {
    id: 4,
    序号: 4,
    department: '市场部',
    name: '赵六',
    age: 30,
    phone: '13800138003',
    email: 'zhaoliu@example.com'
  }
])

const tableRef = ref()

// 处理Excel文件导入
const handleFileChange = async (file: UploadFile) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target?.result as ArrayBuffer)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
      console.log(firstSheet,"9999999999999")
      const jsonData = XLSX.utils.sheet_to_json(firstSheet)
      console.log(jsonData,"333333333333333333")
      // 验证导入的数据
      const errors = tableRef.value.validateData(jsonData)
      
      if (errors.length > 0) {
        ElMessage.error(errors.join('\n'))
        return
      }
       
      // 数据验证通过，更新表格数据
      tableData.value = jsonData.map((item: any, index: number) => ({
        ...item,
        id: index + 1
      }))
      
      ElMessage.success('数据导入成功')
    } catch (error) {
      ElMessage.error('文件解析失败')
    }
  }
  reader.readAsArrayBuffer(file.raw!)
}

// 处理选择变更
const handleSelectionChange = (selection: any[]) => {
  console.log('Selected rows:', selection)
}

// 处理行拖拽
const handleRowDrag = ({ oldIndex, newIndex }: { oldIndex: number, newIndex: number }) => {
  const targetRow = tableData.value.splice(oldIndex, 1)[0]
  tableData.value.splice(newIndex, 0, targetRow)
}

// 处理编辑
const handleEdit = (row: any) => {
  console.log('Edit row:', row)
}

// 处理删除
const handleDelete = (row: any) => {
  const index = tableData.value.findIndex(item => item.id === row.id)
  if (index !== -1) {
    tableData.value.splice(index, 1)
  }
}
</script>

<style scoped>
.table-demo {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}
</style>
